<!-- 视频上传  import Upload from '@/components/Upload/videoUpload' -->
<template>
  <div class="upload-video">
    <div v-if="videoUrl" class="have-video">
      <video ref="videoFile" id="videoFile" :src="videoUrl" height="80" width="120"></video>
      <div class="paly-btn">
        <i class="el-icon-video-play" @click="handleOpenVideo"></i>
        <i class="el-icon-delete" @click="handleRemove"></i>
      </div>
    </div>
    <div class="upload-file">
      <input ref="fileInput" :accept="accept" type="file" @change="getFile" :disabled="isUploading">
      <span :class="['up-add', { 'uploading' : isUploading } ]" @click="handleOpenFile">
        <i v-if="!isUploading" :class="[ isUploading ? 'el-icon-loading' : 'el-icon-plus']"></i>
        <el-progress :width="70" v-else class="upload-progress" type="circle" :percentage="upLoadPercentage"></el-progress>
      </span>
    </div>

    <el-dialog class="play-video" :visible.sync="dialogVisible" append-to-body width="800px" :close-on-click-modal="false"
               @close="handleCloseVideo">
      <video ref="paly-video-el" :src="dialogVideoUrl" controls :width="videoOpen.width - 40" :height="videoOpen.height"></video>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { GetPictureUploadSignData } from '@/api/common'
export default {
  name: 'videoUpload',
  components: {},
  data () {
    return {
      dialogVisible: false,
      isUploading: false,
      videoUrl: '',
      dialogVideoUrl: '',
      videoDuration: 0,
      upLoadPercentage: 0,
      videoOpen: {
        width: 800,
        height: 300
      }
    }
  },
  props: {
    value: {
      tyep: String,
      default: ''
    },
    limitSize: {
      type: Number,
      // 默认500M
      default: 1 * 1024
    },
    accept: {
      // <!--video/*  avi, .mpg, .mpeg, .mp4, 3gpp
      // video/avi, video/mpg, video/mpeg, video/mp4, video/3gpp
      type: String,
      default: 'video/*'
    }
  },
  watch: {
    'value' (val) {
      this.init(val)
    }
  },
  computed: {},
  mounted () {
    this.init()
  },
  methods: {
    init (url) {
      this.videoUrl = this.value
      this.upEmitValue()
    },
    upEmitValue (val) {
      this.$emit('input', val || this.videoUrl)
      this.getVideoTime()
    },
    handleOpenFile () {
      this.$refs.fileInput.dispatchEvent(new MouseEvent('click'))
    },
    getVideoTime () {
      setTimeout(() => {
        if (this.$refs['videoFile']) {
          this.videoDuration = this.$refs['videoFile'].duration
        } else {
          this.videoDuration = 0
        }
        this.$emit('getVideoTime', this.videoDuration)
      }, 800)
    },
    getFile (fileEle) {
      this.isUploading = true
      let file = fileEle.target.files[0] || null
      const fileSize = (file.size / 1000 / 1000).toFixed(0)
      if (fileSize > this.limitSize) {
        this.$message.warning('上传视频文件过大')
        return
      }
      if (file) {
        GetPictureUploadSignData().then(res => {
          const data = res.data
          const host = data.host
          let fileName = file.name
          let suffix = fileName.split('.')[1]
          const moment = new Date().getTime()
          fileName = `${moment}.${suffix}`
          const ossData = {
            'key': `${data.dir}/${fileName}`,
            'policy': data.policy,
            'OSSAccessKeyId': data.accessKeyId,
            'signature': data.signature
          }
          // 图片上传后前置域名
          const vistUrl = data.vistUrl
          this.ossUpload(host, file, ossData, vistUrl)
        }).catch(() => {
          this.removeInputFileValue()
        })
      } else {
        this.$message.warning('请选择视频文件！')
      }
    },
    ossUpload (host, file, ossData, vistUrl) {
      let ossFormData = new FormData()
      for (const key in ossData) {
        ossFormData.append(key, ossData[key])
      }
      ossFormData.append('file', file)
      let that = this
      axios({
        url: host,
        method: 'POST',
        data: ossFormData,
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: function (progressEvent) {
          let total = progressEvent.total
          if (progressEvent.lengthComputable) {
            that.uploadProgress(progressEvent.loaded, total)
          } else {
            that.uploadProgress(total, total)
          }
        }
      }).then(res => {
        this.videoUrl = vistUrl + ossData.key
        this.upEmitValue()
        this.removeInputFileValue()
      }).catch(e => {
        this.$message.error('上传失败！')
        this.removeInputFileValue()
      })
    },
    uploadProgress (loaded, total) {
      this.upLoadPercentage = parseFloat(((loaded / total) * 100).toFixed(2))
    },
    removeInputFileValue () {
      this.isUploading = false
      this.upLoadPercentage = 0
      if (this.$refs.fileInput.value) {
        this.$refs.fileInput.value = ''
      }
    },
    handleCloseVideo () {
      this.$refs['paly-video-el'].pause()
      this.dialogVisible = false
    },
    handleOpenVideo () {
      this.dialogVisible = true
      this.dialogVideoUrl = this.videoUrl
    },
    handleRemove () {
      this.dialogVideoUrl = ''
      this.videoUrl = ''
      this.upEmitValue()
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
